import cv2
import os
import numpy as np
from PIL import Image
  
# 人脸数据路径
path = 'imdata'

detector = cv2.CascadeClassifier("C:/Users/Administrator/Desktop/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml")
recognizer = cv2.face.LBPHFaceRecognizer_create()

def getImagesAndLabels(path):
    imagePaths = [os.path.join(path,f) for f in os.listdir(path)]
    faceSamples = []
    ids = []
    for imagePath in imagePaths:
        PIL_img = Image.open(imagePath).convert('L')   #打开变成灰度图
        img_numpy = np.array(PIL_img, 'uint8') #数组转换
        id = int(os.path.split(imagePath)[-1].split(".")[0])
        faces = detector.detectMultiScale(img_numpy)
        for (x, y, w, h) in faces:
            faceSamples.append(img_numpy[y:y + h, x: x + w])
            ids.append(id)
    return faceSamples, ids

faces, ids = getImagesAndLabels(path) #获取图像数组和id标签数组
recognizer.train(faces, np.array(ids))
recognizer.save('trainner.yml')
